/**
 * 
 */
package anysware.gwt.client.ui;

import anysware.gwt.client.ApplicationEvent;
import anysware.gwt.client.ApplicationEventSource;
import anysware.gwt.client.ApplicationListener;
import anysware.gwt.client.ApplicationListenerSupport;
import anysware.gwt.client.EventConstants;

import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.KeyboardListenerAdapter;
import com.google.gwt.user.client.ui.SuggestBox;
import com.google.gwt.user.client.ui.Widget;

/**
 * TODO: doc me
 * 
 * @author keke<keke@codehaus.org>
 * @revision $Revision: 103 $
 * @version
 */
public class SearchBar extends Composite implements ClickListener,
        ApplicationEventSource {
	private Button	                   button;
	private SuggestBox	               searchBox;
	private ApplicationListenerSupport	support;

	public SearchBar() {
		super();
		final HorizontalPanel outer = new HorizontalPanel();
		outer.add(searchBox = new SuggestBox());
		outer.add(button = new Button(AnyswareApplicationFrame.CONSTANTS
		        .searchButton()));
		searchBox.ensureDebugId("searchBox");
		button.setStyleName("searchBtn");
		initWidget(outer);
		setStyleName("search-bar");
		button.addClickListener(this);
		searchBox.addKeyboardListener(new KeyboardListenerAdapter() {

			/*
			 * (non-Javadoc)
			 * 
			 * @see com.google.gwt.user.client.ui.KeyboardListenerAdapter#onKeyPress(com.google.gwt.user.client.ui.Widget,
			 *      char, int)
			 */
			@Override
			public void onKeyPress(final Widget sender, final char keyCode,
			        final int modifiers) {
				if (keyCode == KEY_ENTER) {
					doSearch();
				}
			}
		});
	}

	/**
	 * @param listener
	 * @see anysware.gwt.client.ApplicationListenerSupport#addListener(anysware.gwt.client.ApplicationListener)
	 */
	public void addListener(final ApplicationListener listener) {
		if (support == null) {
			support = new ApplicationListenerSupport();
		}
		support.addListener(listener);
	}

	public void onClick(final Widget sender) {
		doSearch();
	}

	/**
	 * @param listener
	 * @see anysware.gwt.client.ApplicationListenerSupport#removeListener(anysware.gwt.client.ApplicationListener)
	 */
	public void removeListener(final ApplicationListener listener) {
		if (support != null) {
			support.removeListener(listener);
		}
	}

	private void doSearch() {
		if (support != null) {
			support.fireEvent(new ApplicationEvent(this,
			        EventConstants.SEARCH_EVENT, searchBox.getText()));
		}
	}
}
